using System;
using Microsoft.SPOT;
using System.IO.Ports;
using System.Text;
using NetMf.CommonExtensions;


namespace AstroX
{
    class DiagnosticControl
    {
        private SerialPort _diagnostics;
        Boom _diagnosticBoom;
        PowerControl _diagnosticPower;
        public DiagnosticControl(SerialPort diagnostics, Boom diagnosticBoom, PowerControl diagnosticPower)
        {
            _diagnostics = diagnostics;
            _diagnosticBoom = diagnosticBoom;
            Program.Print("Diagnostic system is operational!");
            diagnostics.DataReceived += new SerialDataReceivedEventHandler(diagnostics_DataReceived);

        }

        void diagnostics_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (e.EventType == SerialData.Eof)
            {
                byte[] buffer=new byte[_diagnostics.BytesToRead];
                _diagnostics.Read(buffer, 0, buffer.Length);
                var message=Encoding.UTF8.GetChars(buffer);
                if (message[0] == 's')
                {
                    Program.Print("Diagnostic shutdown");
                    _diagnosticPower.ShutDown();
                }
                else if (message[0] == 'p')
                {
                    Program.Print("Diagnostic PowerOff");
                    _diagnosticPower.PowerOff(null);
                }
                else if (message[0] == 'o')
                {
                    Program.Print("Diagnostic Open");
                    _diagnosticBoom.Open();
                }
                else if (message[0] == 'c')
                {
                    Program.Print("Diagnostic Close");
                    _diagnosticBoom.Close();
                }
                else if (message[0] == 'a')
                {
                    StringBuilder sb = new StringBuilder();
                    
                    for (int i = 1; i < message.Length; i++)
                    {
                        sb.Append(message[i].ToString());
                    }
                    int position = int.Parse(sb.ToString());
                    _diagnosticBoom.SetPosition(position);
                }

            }
        }
    }
}
